package com.zh.config.utils

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.HttpURLConnection
import java.net.URL

class VideoCache {
    private var scope = MainScope()

    fun startDownload(videoUrl: String, videoSize: (Int) -> Unit) {
        scope = MainScope()
        scope.launch(Dispatchers.IO) {
            try {
                Log.d("fileSize", "video size get : $videoUrl")
                val url = URL(videoUrl)
                val connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET" // 使用HEAD方法仅获取响应头
                connection.connectTimeout = 5000 // 设置连接超时时间
                connection.readTimeout = 5000 // 设置读取超时时间
                connection.connect()
                val responseCode = connection.responseCode
                if (connection.responseCode == HttpURLConnection.HTTP_MOVED_TEMP ||
                    connection.responseCode == HttpURLConnection.HTTP_MOVED_PERM
                ) {//重定向
                    this.cancel()
                    connection.disconnect()
                    val url2 = URL(connection.getHeaderField("Location"))
                    startDownload(url2.toString(), videoSize)
                } else if (responseCode == HttpURLConnection.HTTP_OK) {
                    val contentLength = connection.getHeaderField("Content-Length")
                    if (contentLength != null) {
                        val fileSize = contentLength.toLong()
                        Log.d("fileSize", "video size get : File size: $fileSize bytes")
                        withContext(Dispatchers.Main) {
                            videoSize.invoke(fileSize.toInt())
                        }
                    } else {
                        Log.d("fileSize", "video size get : Content-Length header not found.")
                        withContext(Dispatchers.Main) {
                            videoSize.invoke(0)
                        }
                    }
                } else {
                    withContext(Dispatchers.Main) {
                        videoSize.invoke(0)
                    }
                    Log.d(
                        "fileSize",
                        "video size get : Failed to open connection. Response code: $responseCode"
                    )
                }
                connection.disconnect()
                this.cancel()
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    videoSize.invoke(0)
                }
            }
        }
    }
}